<template>
  <div class="CompanyEdit-page">
    <!-- 页面-公司信息-新增/编辑 -->
    <Form :model="formInfo" ref="companyEditForm" :rules="rules" :label-width="130">
      <!-- 公司编码 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item :label="$t('module.orgManage.companyCode')" prop="companyCode">
            <Input
              v-model.trim="formInfo.companyCode"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :disabled="companyInfo.id != undefined"
              v-bind:readonly="canNotBeEdit"
              :maxlength="30"
            ></Input>
          </Form-item>
        </Col>
        <!-- 公司名称 -->
        <Col span="12">
          <Form-item :label="$t('module.orgManage.companyName')" prop="companyName">
            <Input
              v-model.trim="formInfo.companyName"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :maxlength="80"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 公司简称 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item :label="$t('module.orgManage.companyShort')" prop="companyShort">
            <Input
              v-model="formInfo.companyShortName"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :maxlength="80"
            ></Input>
          </Form-item>
        </Col>
        <!-- 组织机构代码 -->
        <Col span="12">
          <Form-item :label="$t('module.orgManage.orgOrganCode')" prop="orgOrganCode">
            <Input
              v-model="formInfo.companyOrgCode"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :maxlength="80"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 注册地址 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item :label="$t('module.orgManage.registeredAddress')" prop="registeredAddress">
            <Input
              v-model="formInfo.companyAddress"
              :maxlength="80"
              :placeholder="$t('module.orgManage.pleaseInput')"
            ></Input>
          </Form-item>
        </Col>
        <!-- 详细地址 -->
        <Col span="12">
          <Form-item :label="$t('module.orgManage.detailedAddress')" prop="detailedAddress">
            <Input
              v-model="formInfo.companyAddressDesc"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :maxlength="80"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 法定代表人 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item :label="$t('module.orgManage.legalRepresentative')" prop="legalRepresentative">
            <Input
              v-model="formInfo.companyLegalRepr"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :maxlength="80"
            ></Input>
          </Form-item>
        </Col>
        <!-- 注册资本 -->
        <Col span="12">
          <Form-item :label="$t('module.orgManage.registeredCapital')" prop="registeredCapital">
            <InputNumber
              :min="0"
              :max="9999"
              v-model="formInfo.companyRegAssets"
              :placeholder="$t('module.orgManage.pleaseInput')"
            ></InputNumber>
            <span>{{ $t("module.orgManage.tenThousandYuan") }}</span>
          </Form-item>
        </Col>
      </Row>
      <!-- 成立日期 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item :label="$t('module.orgManage.establishDate')" prop="establishDate">
            <!-- v-model="formInfo.companyRegDate" -->
            <DatePicker
              :transfer="true"
              type="date"
              :placeholder="$t('module.orgManage.pleaseSelect')"
              format="yyyy-MM-dd"
              @on-change="companyRegDateChange"
              :value="formInfo.companyRegDate"
              style="width: 100%;"
            />
          </Form-item>
        </Col>
        <!-- 状态 -->
        <Col span="12">
          <Form-item prop="status" :label="$t('common.status')">
            <RadioGroup v-model="formInfo.enabled">
              <Radio :label="1">{{ $t("common.valid") }}</Radio>
              <Radio :label="0">{{ $t("common.invalid") }}</Radio>
            </RadioGroup>
            <!-- <Checkbox v-model="formInfo.companyInside" style="display:block">
              {{
              $t("module.orgManage.domesticInstitutions")
              }}
            </Checkbox> -->
          </Form-item>
        </Col>
      </Row>
      
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="companyInside" :label="$t('module.orgManage.domesticInstitutions')">
            <!-- <RadioGroup v-model="formInfo.companyInside">
              <Radio :label="1">{{ $t("common.yes") }}</Radio>
              <Radio :label="0">{{ $t("common.no") }}</Radio>
            </RadioGroup> -->
            <Radio v-model="formInfo.companyInside">{{ $t("common.yes") }}</Radio>
            <Radio v-model="formInfo.companyInside" :true-value="false" :false-value="true">{{ $t("common.no") }}</Radio>
          </Form-item>
        </Col>
        
      </Row>
      
      <Row :gutter="32" class="code-row-bg">
        <!-- 统一社会信用代码 -->
        <Col span="12"  v-if="formInfo.companyInside">
          <Form-item
            :label="$t('module.orgManage.unifiedSocialCreditCode')"
            prop="unifiedSocialCreditCode"
          >
            <Input
              v-model="formInfo.companyCreditCode"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :maxlength="80"
            ></Input>
          </Form-item>
        </Col>
        <!-- 纳税人标识 -->
        <Col span="12" v-if="formInfo.companyInside">
          <Form-item
            :label="$t('module.orgManage.taxpayerIdentification')"
            prop="taxpayerIdentification"
          >
            <Input
              v-model="formInfo.companyTaxpayer"
              :placeholder="$t('module.orgManage.pleaseInput')"
              :maxlength="80"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 营业期限(看下，绑定的数据比较特殊,应该是数组，但字段是分为两个，还需要看下) -->
      <Row :gutter="32" class="code-row-bg" v-if="formInfo.companyInside">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.businessTerm')" prop="businessTerm">
            <DatePicker
              type="date"
              ref="companyBusTermStart"
              :placeholder="$t('module.orgManage.pleaseSelect')"
              :value="formInfo.companyBusTermStart"
              @on-change="onStartDateChange"
              :options="startDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 40%;"
              
            ></DatePicker>
            <span>-</span>
            <DatePicker
              type="date"
              ref="companyBusTermEnd"
              :placeholder="$t('module.orgManage.permanent')"
              :value="formInfo.companyBusTermEnd"
              @on-change="onEndDateChange"
              :options="endDateOptions"
              :transfer="true"
              :editable="false"
              :clearable="false"
              placement="bottom-end"
              style="width: 40%;"
              
            ></DatePicker>
          </Form-item>
        </Col>
      </Row>
      <!-- 邓白氏编码 -->
      <Row :gutter="32" class="code-row-bg" v-else>
        <Col span="24">
          <Form-item :label="$t('module.orgManage.dunsCode')" prop="dunsCode">
            <Input
              v-model="formInfo.companyDunsNum"
              :placeholder="$t('module.orgManage.pleaseInput')"
              style="width:250px"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 经营范围 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.businessScope')" prop="businessScope">
            <Input
              v-model="formInfo.companyBusScope"
              :placeholder="$t('module.orgManage.pleaseInput')"
              type="textarea"
              :rows="4"
              :maxlength="200"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 营业执照（还不做） -->
      <!-- <Row :gutter="32" class="code-row-bg">
      <Col span="24">
        <Form-item :label="$t('module.orgManage.businessLicense')" prop="businessLicense">
          <Upload action="//jsonplaceholder.typicode.com/posts/">
              <i-button type="ghost" icon="ios-cloud-upload-outline">上传文件</i-button>
          </Upload>
        </Form-item>
      </Col>
      </Row>-->
      <!-- 拓展属性-模板- -->
      <!-- <Row v-if="isShowTemplate"  :gutter="20" class="code-row-bg">
        <p class="extendedAttrTitle">{{extendedAttrTitle}}</p>
        <Col span="24">
          <Form-item :label="$t('module.orgManage.template')" prop="template">
            <Select
              @on-change="changeSelect"
              v-model="formInfo.attributeContext"
              class="no-borderColor"
            >
              <Option
                v-for="(item,index) in companyTemplateList"
                :key="index"
                :value="item.id"
              >{{item.templateName}}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>-->
    </Form>
    <div v-if="isShowTemplate" class="extendClass">
      <p class="extendedAttrTitle">{{extendedAttrTitle}}</p>
      <span style="font-size:14px;padding-right:9px;">{{$t('module.orgManage.template')}}</span>
      <Select
        @on-change="changeSelect"
        v-model="formInfo.attributeContext"
        class="no-borderColor"
        style="width:40%"
      >
        <Option
          v-for="(item,index) in companyTemplateList"
          :key="index"
          :value="item.id"
          :style="{ color:item.status == 2?'#bcbcbc!important': '' }"
        >{{item.templateName}}</Option>
      </Select>
      <div
        class="assign-tree-dimension"
        ref="treeRoot"
        v-if="formInfo.attributeContext && isHintShow"
      >
        <span
          class="operation-hint"
          style="margin-left: 0;"
        >{{ $t("module.treeManage.templateNull") }}</span>
      </div>
      <form-create
        class="create-form-wrap-company"
        v-if="isShow"
        v-model="fcApi"
        :rule="ruleData"
        :option="option"
      ></form-create>
    </div>
    <!-- <form-create class="create-form-wrap-company" v-if="isShow" v-model="fcApi" :rule="ruleData" :option="option"></form-create> -->
    <!-- <div id="form-create"></div> -->
  </div>
</template>
<style>
.no-borderColor .ivu-select-selection {
  border-color: #dddee1 !important;
}
</style>
<script>
import { addCompany, updateCompany } from "@/api/orgApi.js";
import { getCompanyTemplateList, templateDetail } from "@/api/extendAttrApi.js";
import { getValueSetCode } from "@/api/valuesetCodeApi.js";
import locales from "../locales.js";
import { codeReg } from "@/const.js";

// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  mixins: [locales],
  components: {},
  props: {
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    companyInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    // 公司编码-不符合字段规则的错误提示
    const validateCompanyCode = (rule, value, callback) => {
      //当明细页面不允许编辑时，不做合法性校验
      if (this.canNotBeEdit) {
        callback();
        return;
      }
      if (value == null || value === "") {
        callback(new Error(this.$t("module.orgManage.enterCompanyCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    // 公司名称-不符合字段规则的错误提示
    const validateCompanyName = (rule, value, callback) => {
      //当明细页面不允许编辑时，不做合法性校验
      if (this.canNotBeEdit) {
        callback();
        return;
      }
      if (value == null || value === "") {
        callback(new Error(this.$t("module.orgManage.enterCompanyName")));
      }
      callback();
    };
    return {
      formInfo: {
        companyCode: "", // 公司编码
        companyName: "", // 公司名称
        companyShortName: "", // 公司简称
        companyOrgCode: "", // 组织机构代码
        companyAddress: "", // 注册地址
        companyAddressDesc: "", // 详细地址
        companyLegalRepr: "", // 法定代表人
        companyRegAssets: 0, // 注册资本
        companyRegDate: "", // 成立日期
        enabled: 1, // 状态
        companyInside: true, //境内机构标识
        companyCreditCode: "", // 统一社会信用代码
        companyTaxpayer: "", // 纳税人标识
        companyBusTermStart: "", // 营业期限开始时间(绑定的数据比较特殊，还需要看下)
        companyBusTermEnd: "", // 营业期限结束时间(绑定的数据比较特殊，还需要看下)
        companyBusTermLang: false, // 营业期限(长期)
        companyDunsNum: "", // 邓白氏编码
        companyBusScope: "", //经营范围
        attributeContext: "" // 扩展属性模板
      },
      fcApi: null,
      companyTemplateList: [],
      isShowTemplate: true,
      formConfig: {
        rule: [],
        option: {}
      },
      ruleList: [],
      // 字段规则
      rules: {
        companyCode: [{ validator: validateCompanyCode, trigger: "blur", required: true }],
        companyName: [{ validator: validateCompanyName, trigger: "blur", required: true }]
      },
      isShow: false,
      isHintShow: false,
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.onOk();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    canNotBeEdit: function() {
      if (this.isReadOnly) {
        return true;
      }
      return false;
    },
    extendedAttrTitle: function() {
      return this.$t("module.orgManage.extendedAttr");
    },
    option() {
      return {
        resetBtn: false,
        submitBtn: false,
        form: {
          labelWidth: 100,
          size: "default"
        }
      };
    },
    fcOption() {
      return {
        global: {
          "*": {
            col: {
              span: 12
            },
            props: {
              width: "355px",
              disabled: !this.isEdit
            }
          }
        },
        form: {
          labelWidth: 100,
          size: "default"
        }
      };
    },
    ruleData() {
      return this.ruleList;
    },
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.formInfo.companyBusTermEnd == "object") {
            // 日期是日期对象，如 new Date()
            return (
              date &&
              date.valueOf() < Date.now() - ONE_DAY &&
              date.valueOf() > _this.formInfo.companyBusTermEnd.valueOf() - ONE_DAY
            );
          } else if (typeof _this.formInfo.companyBusTermEnd == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.formInfo.companyBusTermEnd.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.formInfo.companyBusTermStart == "object") {
            // 生效日期是日期对象，如 new Date()
            return date && date.valueOf() < _this.formInfo.companyBusTermStart.valueOf() - ONE_DAY;
          } else if (typeof _this.formInfo.companyBusTermStart == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.formInfo.companyBusTermStart.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },
  mounted() {},
  created: function() {
    if (this.companyInfo.id) {
      this.$emit("SetTitle", this.$t("module.orgManage.editCompany"));
      const _companyInfo = this.companyInfo;
      this.formInfo = {
        companyCode: _companyInfo.companyCode, // 公司编码
        companyName: _companyInfo.companyName, // 公司名称
        companyShortName: _companyInfo.companyShortName, // 公司简称
        companyOrgCode: _companyInfo.companyOrgCode, // 组织机构代码
        companyAddress: _companyInfo.companyAddress, // 注册地址
        companyAddressDesc: _companyInfo.companyAddressDesc, // 详细地址
        companyLegalRepr: _companyInfo.companyLegalRepr, // 法定代表人
        companyRegAssets: _companyInfo.companyRegAssets, // 注册资本
        companyRegDate: _companyInfo.companyRegDate, // 成立日期
        enabled: _companyInfo.enabled, // 状态
        companyInside: _companyInfo.companyInside == 0 ? false : true, //境内机构标识
        companyCreditCode: _companyInfo.companyCreditCode, // 统一社会信用代码
        companyTaxpayer: _companyInfo.companyTaxpayer, // 纳税人标识
        companyBusTermStart: this.formatDateTime(_companyInfo.companyBusTermStart),
        companyBusTermEnd:
          _companyInfo.companyBusTermEnd == null ? "" : this.formatDateTime(_companyInfo.companyBusTermEnd),
        companyBusTermLang: _companyInfo.companyBusTermLang == 0 ? false : true, // 营业期限(长期)
        companyDunsNum: _companyInfo.companyDunsNum, // 邓白氏编码
        companyBusScope: _companyInfo.companyBusScope, //经营范围
        attributeContext: _companyInfo.attributeContext // 扩展属性模板
      };
      this.ruleList = _companyInfo.attributeValue ? _companyInfo.attributeValue.template : [];
      this.isShow = true;
    } else {
      this.$emit("SetTitle", this.$t("module.orgManage.newCompany"));
      this.formInfo.companyBusTermStart = new Date()
        .toISOString()
        .replace(/T.*/, " ")
        .trim();
      this.formInfo.companyBusTermEnd = "2099-12-31";
    }

    this.$emit("SetPageWidth", 800);
    this.$emit("SetPageActions", this.actions);
    this.getCompanyTemplate([1]);
  },
  methods: {
    onStartDateChange(date) {
      this.formInfo.companyBusTermStart = date;
    },
    onEndDateChange(date) {
      this.formInfo.companyBusTermEnd = date;
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      var time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      var Y = time.getFullYear() + "-";
      var M = this.addZero(time.getMonth() + 1) + "-";
      var D = this.addZero(time.getDate()) + " ";
      var h = this.addZero(time.getHours()) + ":";
      var m = this.addZero(time.getMinutes()) + ":";
      var s = this.addZero(time.getSeconds());
      return Y + M + D;
    },
    // 选择成立日期
    companyRegDateChange(date) {
      this.formInfo.companyRegDate = date;
    },
    // 获取公司模板数据
    getCompanyTemplate(statusList) {
      getCompanyTemplateList(statusList).then(res => {
        if (res.data.length == 0) {
          this.isShowTemplate = false;
          return;
        }
        this.companyTemplateList = res.data;
        // 获取已归档模板（意义相当于选择以后被无效的模板）
        this.templateDetail(this.formInfo.attributeContext, "pigeonhole");
      });
    },
    // 保存
    onOk() {
      const newFormData = {};
      if (this?.fcApi?.formData) {
        const formData = this.fcApi.formData();
        const rules = this.fcApi.rule;
        for (const r of rules) {
          newFormData[r.matchColumn] = r.type === 'checkbox'
            ? JSON.stringify(formData[r.field])
            : formData[r.field];
        }
      }
      let params = {
        ...this.formInfo,
        companyInside: this.formInfo.companyInside == false ? 0 : 1,
        companyBusTermLang: this.formInfo.companyBusTermLang == false ? 0 : 1,
        // tenantCode: "0000",
        tenantCode: this.tenantCode,
        id: this.companyInfo.id ? this.companyInfo.id : "",
        attributeValue: {
          template: this.ruleData
        },
        ...newFormData
      };
      this.$refs["companyEditForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.companyInfo.id) {
            updateCompany(params)
              .then(data => {
                this.loading = false;
                this.$message.success({
                  content: this.$t("module.orgManage.updateSuccess"),
                  duration: 3
                });
                this.modal = false;
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          } else {
            addCompany(params)
              .then(data => {
                this.loading = false;
                this.$message.success({
                  content: this.$t("module.orgManage.createSuccess"),
                  duration: 3
                });
                this.modal = false;
                this.$emit("Close", true);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error(this.$t("common.formValidateFailed"));
        }
      });
    },
    // // 切换模板
    // changeSelect(val) {
    //   templateDetail(val).then(res => {
    //     this.ruleList = res.data.attributeContent.template;
    //     this.isShow = true;
    //   });
    // },
    // 切换模板
    changeSelect(val) {
      this.templateDetail(val, "changeSelect");
    },
    // 获取模板详情
    templateDetail(val, sign) {
      templateDetail(val).then(res => {
        if (sign == "pigeonhole") {
          const arr = [...this.companyTemplateList, res.data || {}];
          const obj = {};
          this.companyTemplateList = arr.filter(d => {
            if (d.id && !obj[d.id]) {
              obj[d.id] = true;
              return true;
            }
          });
          const templateList = res?.data?.attributeContent?.template || []
          const { companyInfo } = this
          this.ruleList = templateList.map(t => {
            const item = {
              ...t,
              value: t.type === 'checkbox' && t?.matchColumn
                ? companyInfo?.[t?.matchColumn]
                  ? JSON.parse(companyInfo?.[t?.matchColumn])
                  : []
                : companyInfo?.[t?.matchColumn] || ''
            }
            return item
          })
        } else {
          this.ruleList = res.data.attributeContent.template;
          this.isShow = true;
          this.isHintShow = this.ruleList.length == 0;
        }
      });
    }
  }
};
</script>
<style lang="less">
.CompanyEdit-page {
  .extendedAttrTitle {
    font-size: 14px;
    font-weight: bold;
    border-bottom: 0 !important;
    line-height: 14px !important;
    margin-bottom: 20px;
  }
  .create-form-wrap-company {
    margin-top: 20px;
    // margin-left: -10px;
    padding: 0;
    .ivu-form-item {
      display: flex;
      justify-content: space-between;
      .ivu-form-item-label {
        width: auto !important;
        min-width: 69px !important;
        max-width: 188px !important;
      }
      .ivu-form-item-content {
        margin-left: 0 !important;
        flex: 1;
        .ivu-input-number {
          width: 100% !important;
        }
      }
    }
  }
  .extendClass {
    border: 1px solid #eee;
    padding: 20px;
    margin-left: 0 !important;
  }
}
</style>
